
/*

*/
#include <iostream>

#include "utils/timer.h"
#include "utils/FileLock.h"
#include "log/syslog.h"
#include "application.h"

using namespace std;
using namespace equip_system;

#define TAG "main()"

//Log for recording the system running.
system_log::CSysLog syslog;

// 设置locale，让cout支持UTF - 8输出
void setupUTF8Output()
{
#ifdef _WIN32
    // Windows系统
    system("chcp 65001 > nul"); // 把控制台编码设置为UTF - 8
    // setlocale(LC_ALL, "chs");   // 设置本地环境
#else
    // Linux/Mac系统
    setlocale(LC_ALL, "en_US.UTF-8");
#endif
}
/*

*/
int main()
{
    try
    {
        /**
         * 
         */
        // 错误：SingleInstance 改为 Singleton
        auto &instance = equip_system::Singleton::getInstance("EquipServer.lock");
        // Singleton instance("EquipServer"); // Windows路径
        // SingleInstance instance("/var/run/my_app.lock"); // Linux路径
        if (instance.isAnotherInstanceRunning())
        {
            std::cerr << "main_>>>[Error]:应用程序已在运行!" << std::endl;
            return 1;
        }

        /**
         * 
         */
        const size_t maxFileSize = 1024 * 1024 * 5; // 5M
        const size_t maxFiles = 10;                 // num=10
        std::string _name = "./log/equip_record-" + Timer::getCurrentDateTime(data_time_format::FMT_YYMMDDHHMMSS) + ".log";
        system_log::CSysLog syslog; // 声明syslog对象
        if (0 != syslog.init(_name.c_str(), maxFileSize, maxFiles))
        {
            cerr << "main_>>>[Error]:Failed to initialize syslog! Check log directory or permissions." << endl;
            return 1; // 初始化失败时退出程序
        }

        //
        setupUTF8Output();

        string _infor;
        _infor = "Start EquipServer(press Ctrl+C to exit) ...";
        ES_LOG(TAG, LEVEL_INFO, _infor.c_str());
        // syslog.print(_infor.c_str());

        // Launch the application
        int startResult = Application::GetInstance().Start();
        if (startResult != 0)
        {
            ES_LOG(TAG, LEVEL_ERROR, "Application start failed with code: %d", startResult);
            return startResult;
        }

        /**
         * 
         */
        _infor = "Program exited...";
        ES_LOG(TAG, LEVEL_INFO, _infor.c_str());
        // syslog.print(_infor.c_str());

        return 0;
    }
    catch (const std::exception &e)
    {
        std::cerr << "main_>>>[Error]: " << e.what() << std::endl;
        return 1;
    }
}
